# -*- coding: utf-8 -*- 

#from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import xmpp_handlers
from google.appengine.ext import db
import logging
import datetime
import setting
import tools.short_url as short_url
import api

from base import *

from model import ShareCategory,ShareLink,ShareCategoryLink,_today

class Login(BaseRequestHandler):
    def get(self):
        self.login()

class Logout(BaseRequestHandler):
    def get(self):
        self.logout()

class AdminTemp(BaseRequestHandler):
    def get(self, slug=None):
        self.response.out.write('done')

class GetSiteMap(BaseRequestHandler):
    def get(self):
        urls = []
        
        def addurl(loc,lastmod=None,changefreq=None,priority=None):
            url_info = {
                'location':   loc,
                'lastmod':	lastmod,
                'changefreq': changefreq,
                'priority':   priority
            }
            urls.append(url_info)

        addurl('http://pythias01.appspot.com',changefreq='daily',priority=0.9)

        # categories
        categories = ShareCategory.all()
        categories.order('-name')
        for category in categories:
            addurl('http://pythias01.appspot.com/share/category/%s'%category.name,changefreq='daily',priority=0.5)
        
        today = _today()
        yesterday = today + datetime.timedelta(days=-1)
        shares = ShareLink.all().filter('date >', yesterday)
        for share in shares:
            addurl('http://pythias01.appspot.com/share/view/%s'%(share.name),changefreq='daily',priority=0.4)

        self.render("views/sitemap.xml",{'urlset':urls})

class GetRSS(BaseRequestHandler):
    def get(self):
        today = _today()
        yesterday = today + datetime.timedelta(days=-1)
        shares = ShareLink.all().filter('date >', yesterday)
        
        last_updated = datetime.datetime.now()
        last_updated = last_updated.strftime("%a, %d %b %Y %H:%M:%S +0000")

        values={
            'shares':shares,
            'last_updated':last_updated,
        }
        
        html = self.get_render("views/rss.html",values)
        self.response.headers['Content-Type'] = 'application/rss+xml'
        self.write(html)

class GetSharesByDate(BaseRequestHandler):
    def get(self, year, month, day):
        # get date
        today = datetime.date(int(year), int(month), int(day))
        yesterday = today + datetime.timedelta(days=-1)
        tomorrow = today + datetime.timedelta(days=+1)

        # sites
        shares = ShareLink.all().filter('date >', yesterday).filter('date <', tomorrow)

        show_tomorrow = tomorrow <= datetime.date.today()
        
        values={
            'shares':shares,
            'date':today,
            'yesterday':yesterday,
            'tomorrow':tomorrow,
            'show_tomorrow':show_tomorrow,
        }

        self.render("views/white/date.html",values)

class GetSharesByCategory(BaseRequestHandler):
    def get(self, category_name):
        page = self.request.get('p')
        if page == None or page == '':
            page = 1
        else:
            page = int(page)

        # categories
        category = ShareCategory.get_by_key_name(category_name)
        if category == None:
            return self.error_page("404")

        # shares
        shares = []
        category_links = category.category_links
        for category_link in category_links:
            shares.append(category_link.link)
        #shares.order('-date')
    
        share_count = len(shares)
        max_page = share_count / setting.COUNT_PER_PAGE + ( share_count % setting.COUNT_PER_PAGE and 1 or 0 )

        if page < 1 or page > max_page and max_page != 0:
            return self.error_404()
            
        offset = (page-1) * setting.COUNT_PER_PAGE
        shares = shares[offset:offset+setting.COUNT_PER_PAGE]

        show_prev = shares and (not (page == 1))
        show_next = shares and (not (page == max_page))

        shares.sort(compare)

        values={
            'shares':shares,
            'category' : category,
            'show_prev':show_prev,
            'show_next':show_next,
            'page_index':page,
        }
        
        self.render("views/white/category.html",values)

def compare(a, b):
    return cmp(b.date, a.date)

class CreateCategory(BaseRequestHandler):
    @requires_admin
    def get(self):
        self.render("views/white/category_create.html",{})
    
    @requires_admin
    def post(self):
        name = self.request.get('name')
        title = self.request.get('title')
        description = self.request.get('description')

        category = ShareCategory.get_by_key_name(name)
        
        # 已经存在
        if category:
            pass
        else:
            category = ShareCategory(key_name = name)
            category.name = name
            category.title = title
            category.description = description
            category.put()

        values={}
        
        self.render("views/white/category_create.html",values)

class GetLinkInfo(BaseRequestHandler):
    def get(self):
        link = self.request.get('link')
        success = False
        
        values = {}
        if link:
            import tools.get_link_info as get_link_info
            name,title,pictures = get_link_info.get_link_info(link)
            picture_count = len(pictures)
            pictures = '|'.join(pictures)

            values['name'] = name
            values['title'] = title
            values['pictures'] = pictures
            values['picture_count'] = picture_count

            success = True
        else:
            success = False

        values['success'] = success

        import simplejson as simplejson
        html = simplejson.dumps(values)

        self.response.out.write(html)

class CreateShare(BaseRequestHandler):
    @requires_admin
    def get(self):
        link = self.request.get('link')
        values={'link':link}
        
        self.render("views/white/share_create.html",values)
    
    @requires_admin
    def post(self):
        title = self.request.get('title')
        description = self.request.get('description')
        categories = self.request.get_all('categories')
        picture = self.request.get('picture')
        link = self.request.get('link')

        if not picture:
            picture = 'http://www.google.com/logos/2010/ersoy10-hp.jpg'
        
        name = short_url.random_shortcut()

        length = 4
        share = ShareLink.get_by_key_name(name)
        while share:
            length += 1
            name = short_url.random_shortcut(length)
            share = ShareLink.get_by_key_name(name)

        share = ShareLink(key_name = name)
        share.name = name
        share.title = title
        share.description = description
        share.link = link
        share.user = users.get_current_user()
        share.picture = picture
        share.date = datetime.datetime.utcnow() + datetime.timedelta(hours=+8)
        share.put()

        # categories
        logging.info('categories %s'%categories)
        for category in categories:
            category_entity = ShareCategory.get_by_key_name(category)
            logging.info('category_entity %s'%category_entity)
            categorylink = ShareCategoryLink(category=category_entity, link=share)
            categorylink.put()

        values={}
        
        self.render("views/white/share_create.html",values)

class ViewShare(BaseRequestHandler):
    def get(self, name):
        share = ShareLink.get_by_key_name(name)
        
        if share == None:
            return self.error_404()
        
        share.increase_view_count()
        self.render("views/white/share_view.html", {'share':share})

class LinkShare(BaseRequestHandler):
    def get(self, name):
        share = ShareLink.get_by_key_name(name)
        
        if share == None:
            return self.error_404()
        
        result = urlfetch.fetch(url=share.link)
        
        self.write(result.content)

class GetShares(BaseRequestHandler):
    def get(self):
        
        page = self.request.get('p')
        if page == None or page == '':
            page = 1
        else:
            page = int(page)

        # shares
        shares = ShareLink.all()
        shares.order('-date')
    
        share_count = shares.count()
        max_page = share_count / setting.COUNT_PER_PAGE + ( share_count % setting.COUNT_PER_PAGE and 1 or 0 )

        if page < 1 or page > max_page and max_page != 0:
            return self.error_404()

        shares = shares.fetch(setting.COUNT_PER_PAGE, offset = (page-1) * setting.COUNT_PER_PAGE)

        show_prev = shares and (not (page == 1))
        show_next = shares and (not (page == max_page))

        values={
            'shares':shares,
            'show_prev':show_prev,
            'show_next':show_next,
            'page_index':page,
        }
        
        self.render("views/white/index.html",values)

def main():
    application = webapp.WSGIApplication(
        [
            ('/', GetShares),                                   # 获取今天所有团购
            ('/share', GetShares),                             # 获取今天所有团购
            ('/share/get', GetLinkInfo),                       # 获取今天所有团购
            ('/share/create/share', CreateShare),              # 获取今天所有团购
            ('/share/view/(.*)', ViewShare),                   # 获取今天所有团购
            ('/share/link/(.*)', LinkShare),                   # 获取今天所有团购
            ('/share/create/category', CreateCategory),        # 获取今天所有团购
            ('/share/category/(.*)', GetSharesByCategory),      # 生成所有预设站点
            ('/share/(\d{4})/(\d{2})/(\d{2})', GetSharesByDate),# 获取某天的所有团购
            ('/admin/temp/(.*)', AdminTemp),                    # 临时测试
            ('/share/rss', GetRSS),                             # RSS
            ('/sitemap', GetSiteMap),                           # SiteMap
            ('/login', Login),                           # SiteMap
            ('/logout', Logout),                           # SiteMap
            ('/share/api/get_categories', api.GetCategories),
            ('/share/api/convert', api.ConvertToSAE),
        ],
        debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
